package com.ybwh.outterapi.requst;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ybwh.outterapi.anno.OpenApi;
import com.ybwh.outterapi.codec.AppInfoAccesser;
import com.ybwh.outterapi.codec.AppKeyHolder;
import com.ybwh.outterapi.codec.DataCrypto;
import com.ybwh.outterapi.constant.RequestHeaderProperties;
import com.ybwh.outterapi.exceptions.OpenApiException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;

@Slf4j
@ControllerAdvice
@Order(1)
@AllArgsConstructor
public class SecretRequestAdvice extends RequestBodyAdviceAdapter {

    public static final long TIME_OUT = 60 * 1000;

    private ObjectMapper objectMapper;
    private DataCrypto dataCrypto;
    private AppInfoAccesser appInfoAccesser;


    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {

        //判断class是否存在注解
        if (methodParameter.getContainingClass().getAnnotation(OpenApi.class) != null) {
            return true;
        }
        //判断方法是否存在注解
        return methodParameter.getMethodAnnotation(OpenApi.class) != null;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        IOUtils.copy(inputMessage.getBody(), byteStream);
        byte[] httpBody = dataCrypto.decrypt(appInfoAccesser.getAppSecret(AppKeyHolder.get()), byteStream.toByteArray());
        if (httpBody == null) {
            throw new HttpMessageNotReadableException("request body decrypt error", inputMessage);
        }

        // 检查 时间戳 是否超时
        String json = new String(httpBody, StandardCharsets.UTF_8);
        JsonNode jn = objectMapper.readTree(json);
        JsonNode time = jn.get(RequestHeaderProperties.TIMESTAMP);
        if (null == time) {
            throw new OpenApiException("request body miss paramter timestamp");
        }
        long timestamp = time.asLong();
        if (System.currentTimeMillis() - timestamp > TIME_OUT) {
            throw new OpenApiException("request timeout ");
        }


        //返回处理后的消息体给messageConvert
        return new SecretHttpMessage(new ByteArrayInputStream(httpBody), inputMessage.getHeaders());
    }


}